package com.ccc.poi.tl.controller;

import cn.hutool.core.date.DateUtil;
import com.ccc.poi.tl.service.TestTableService;
import com.deepoove.poi.XWPFTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;

/**
 * 测试word表格模板
 *
 * @author superC
 * @version 1.0.0
 * @date 2023-07-28
 */

@RestController
@RequestMapping("/table")
public class TestTableController {

    @Autowired
    private TestTableService service;

    /**
     * 导出word表格
     *
     * @param response
     */
    @GetMapping("/download")
    public void download(HttpServletResponse response) {
        try {
            String fileName = "table_" + DateUtil.format(LocalDateTime.now(), "yyyyMMddHHmmss") + ".docx";
            XWPFTemplate document = service.exportDoc();
            response.reset();
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            OutputStream os = response.getOutputStream();
            document.write(os);
            os.close();
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
